﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Quartz.Impl;
using Quartz;
using System.IO;
using DailyPhoto.Entities;
using System.Configuration.Install;
using DailyPhoto.Common;

namespace DailyPhoto
{
    public class DailyPhotoService : ServiceBase
    {
        private IScheduler scheduler;
        private DailyPhotoExternalService externService;


        public DailyPhotoService(bool console)
        {
            scheduler = new StdSchedulerFactory().GetScheduler();

            var port = (int)Application.Config.service.port;
            externService = new DailyPhotoExternalService(port);

            if (console)
            {
                this.OnStart(null);
            }
        }

        public DailyPhotoService() : this(false) { }

        protected override void OnStart(string[] args)
        {
            Logger.Write("Daily Photo Started !");
            externService.Start();
            scheduler.Start();

            var job = JobBuilder.Create<DailyPhotoJob>().WithIdentity("dailyphoto").Build();

            var trigger = TriggerBuilder.Create().WithIdentity("dailyphoto")
                         .StartNow().WithCronSchedule("0 27 10 ? * SUN-FRI").Build();

            scheduler.ScheduleJob(job, trigger);
        }

        protected override void OnStop()
        {
            externService.Stop();
            scheduler.Shutdown();

            Logger.Write("Daily Photo Stopped !");
        }
    }

    [RunInstaller(true)]
    public class DailyPhotoInstaller : Installer
    {
        public DailyPhotoInstaller()
        {
            var processInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            var serviceInstaller = new System.ServiceProcess.ServiceInstaller();

            //Process Installer Configuration
            processInstaller.Account = ServiceAccount.User;
            //Service Installer Configuration
            serviceInstaller.DisplayName = "DailyPhoto";
            serviceInstaller.StartType = ServiceStartMode.Automatic;
            serviceInstaller.ServiceName = "dailyphoto";
            //Add Installers
            this.Installers.Add(processInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }

    public class DailyPhotoJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Logger.Write("Scheduler daily photo generation started");
            Util.GenerateDailyPhoto();
            Logger.Write("Scheduler daily photo generation ended");
        }
    }
}
